/**
 * Created by   :chengwei
 * Created time :2017/5/9
 * File explain :施小包账户
 */
require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
	vue: ["./vue2-4-1/vue"],
	header:["../components/my-header"],
    menu:["../components/my-menu"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    bootTable: ["bootstrap-table-dist/dist/js/bootstrap-table"],
    bootTableCN: ["bootstrap-table-dist/dist/locale/bootstrap-table-zh-CN"],
    comConfig: ["../common/js/common-config"]
  }
});
require(["jquery"], function () {
  require(["bootTable"], function () {
    require(["vue","header","menu","zui", "layer", "bootTableCN", "comConfig"], operationCodeFun)
  })
});
function operationCodeFun(vue,header,menu) {
  // 由于使用require框架整合，我们需要为layer.js配置读取css文件的路径
  layer.config({
    path: "../../libs/layer/"
  });
  window.initTop(vue);
  window.initMenu(vue);
  // todo 声明变量
  var QHConfig = $("body").data("config");
  var userDeteail=null;
  var manageDetail = JSON.parse(window.sessionStorage.getItem("detail"));//获得角色信息
  var traderType = {};//交易类型
  var traderStatus = {};//交易状态
    
  //todo 点击事件
  $("#id-trading-record").on("click",".close-trading,.bank-pay-btn",billClickFun);
  
  
  //todo 初始化页面渲染
  //渲染页面基本信息
  getAccountDetail();
  /*
   * 获取施小包账户信息
   * 项目详情接口
   * @author  chengwei
   * @Date    2017/5/9
   * */
  function getAccountDetail() {
    $.ajax(tokenAjax({
      url: QHConfig.url.getSXBInfo,
      contentType: "application/json",
      dataType: "json",
      async:false,
      success: function (data) {
        if (data.status == 200) {
          data = data.data;
          userDeteail=data;
		  getTrader();//获得交易类型
          window.sessionStorage.setItem("detail",JSON.stringify(data));
          //转换金额格式
          data.availableBalance = data.availableBalance == null ? "0.00" :data.availableBalance;
          //转换正常使用和已冻结
          data.status = data.status == "NORMAL" ? "正常使用中" : "已冻结";
          //设置显示金额
          var _small = outputmoney(data.availableBalance);
          //金额整数部分
          $(".big").text(_small.slice(0, _small.length - 3));
          //金额小数部分
          $(".small").text(_small.slice(_small.length - 3, _small.length));

          if (data.status == "正常使用中") {
            //判断是否有支付密码
            if (data.isSetPayPass == false) {
              payPass();
            }
            //点击下面的按钮
            click();
            //交易记录
            tradingRecord();
          } else {
            $(".status").removeClass("not-freeze").addClass("freeze");
            $(".recharge").removeClass("recharge-btn").addClass("gray-recharge-btn");
            $(".cash-btn,.carry-btn,.bank-btn").removeClass("blue-btn").addClass("gray-btn");
            $("main").hide();
          }
          $("header").find("[data-name]").each(function (i, c) {
            var k = $(c).attr("data-name");
            $(c).text(data[k]);
          });
        } else if (data.status == 400) {
          layer.msg("data.message");
        }
      }
    }))
  }
//todo 其他功能函数
  function getTrader() {
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeType+userDeteail.roleId,
      success: function (res) {
        traderType = res.data;//支付类型
      }
    }));
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeStatus,
      success: function (res) {
        traderStatus = res.data;//支付类型
      }
    }));
  }
  //支付密码初始化的提示
  function payPass() {
    layer.confirm("您还未设置支付密码！",
      {
        title: "温馨提示",
        btn: ["以后再说", "现在就去设置"],
      },
      function (index) {
        layer.close(index)
      },
      function () {
		 top.location.href="../../tpl/set-payment-password/set-payment-password.html";
        //parent.$("#id-main-frame").attr("src", "").click();
      }
    );
  }

  //按钮主函数
  function click() {
    //提现
    $(".cash-btn").on("click", function () {
      //var rechargeUrl = `../../tpl/payCash-noten/payCash-noten.html?userCode=${userDeteail.userCode}&balance=${userDeteail.availableBalance}&operName=${userDeteail.realName}`;
      //layerNew(rechargeUrl);
	  window.open(`../../tpl/payCash-noten/payCash-noten.html?userCode=${userDeteail.userCode}&balance=${userDeteail.availableBalance}&operName=${userDeteail.realName}`);
    });
    //转账
    $(".carry-btn").on("click", function () {
      //var rechargeUrl = `../../tpl/buyer-transfer-accounts/buyer-transfer-accounts.html?userCode=${userDeteail.userCode}&balance=${userDeteail.availableBalance}&operName=${userDeteail.realName}&transfer=TRANSFER`;
      //layerNew(rechargeUrl);
	  window.open(`../../tpl/buyer-transfer-accounts/buyer-transfer-accounts.html?userCode=${userDeteail.userCode}&balance=${userDeteail.availableBalance}&operName=${userDeteail.realName}&transfer=TRANSFER`);
    });
    //充值
    $(".recharge").on("click", function () {
      //var rechargeUrl = `../../tpl/project-recharge/project-recharge.html`;
      //layerNew(rechargeUrl);
	  window.open(`../../tpl/project-recharge/project-recharge.html`);
    });
    //银行卡管理
    $(".bank-manage").on("click", function () {
      //var rechargeUrl = `../../tpl/bank-manage/bank-manage.html`;
      //layerNew(rechargeUrl);
	  window.open(`../../tpl/bank-manage/bank-manage.html`);
    });
    //查看全部交易记录
    $(".all-deal").on("click","span", function () {
      //parent.$("#id-main-frame").attr("src", "../../tpl/mdu-deal-record/mdu-deal-record.html").click();
	  window.location.href="../../tpl/mdu-deal-record/mdu-deal-record.html";
    });
  }
  //跳转页面
  function layerNew(url) {
    parent.layer.open({
      title: false,
      shade: 0.8,
      move:false,
      closeBtn:0,
      resize:false,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: url,
     end:function() {
         window.location.reload();
     }
    })
  }
  /*
   * 获取施小包交易记录
   * @author  chengwei
   * @Date    2017/5/10
   * */
  function tradingRecord() {
    $("#id-trading-record").bootstrapTable({
      url: QHConfig.url.getDealRecord,
      ajax:tableAjax,
      queryParams: function (params) {
        params.limit = 5;
        params.pageNum = params.offset / params.limit + 1;
        params.pageSize = params.limit;
        return params;
      },
      responseHandler: function (res) {
        $("#id-trading-record").data("bootstrap.table").options.pageSize = res.data.pageSize;
        return QHConfig.BSTTableResHandler(res, resTradingRecordFmt);
      },
      onLoadSuccess: function () {
        $(".fixed-table-pagination").css("display", "none");
      },
      onClickRow: function(r, tr, i){
        if(i != 5){
          jumpDetails(r);
        }
      }
    });
  }
//点击行到账单详情
  function jumpDetails(row) {
    var txt = "";//当前账单类型
    $.each(traderType, function (k, v) {
      if (v == row.tradeType) {
        txt = k;
      }
    });
    layer.open({
      title: false,
      closeBtn:0,
      shade: 0.8,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: `../../page/check-details/check-details.html?accountBill=${row.id}&type=1&amount=${row.amount}`
      +`&operName=${row.mainAccountRealName}&accountName=${row.oppositeAccountUserCode}`+
      `&tradeMemo=${row.tradeMemo}&bizzSn=${row.bizzSn}&transfer=${txt}&balance=${manageDetail.availableBalance}`+
      `&userCode=${manageDetail.userCode}&bizzSys=${row.bizzSys}&formBill=true`,
      end:function(){
        $("#id-trading-record").bootstrapTable("refresh");
      }
    })
  }

  //交易记录表格数据渲染和格式转换,$data:当前行对象
  function resTradingRecordFmt($data) {
    $data.createdAt = QHConfig.timeFmt($data.createdAt, 2);
    $data.amount = $data.fundFlow == "资金流入" ? "+" + outputmoney($data.amount) : "-" + outputmoney($data.amount);
  }

  //金额三位用逗号分开
  function outputmoney(number) {
    number = number + "".replace(/,/g, ""); //得到的数字里的逗号替换为空
    if (isNaN(number) || number == "") {
      return "";
    } //判断得到的数字是不是NaN和空的类型，返回为空
    number = Math.round(number * 100) / 100; //取小数点后数字进行四舍五入
    if (number < 0)
      return '-' + outputdollars(Math.floor(Math.abs(number) - 0) + '') + outputcents(Math.abs(number) - 0);
    else
      return outputdollars(Math.floor(number - 0) + '') + outputcents(number - 0);
  }

  //格式化金额
  function outputdollars(number) {
    if (number.length <= 3)
      return (number == '' ? '0' : number);
    else {
      var mod = number.length % 3;
      var output = (mod == 0 ? '' : (number.substring(0, mod)));
      for (var i = 0; i < Math.floor(number.length / 3); i++) {
        if ((mod == 0) && (i == 0))
          output += number.substring(mod + 3 * i, mod + 3 * i + 3);
        else
          output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
      }
      return (output);
    }
  }

  //判断小数点后的特殊情况，列入小于10
  function outputcents(amount) {
    amount = Math.round(((amount) - Math.floor(amount)) * 100);
    return (amount < 10 ? '.0' + amount : '.' + amount);
  }
  function billClickFun(){
    var billData=JSON.parse($(this).attr("data-bill"));
    var that=this;
    if($(this).hasClass("close-trading")){
      clickCloseFun(that)
    }else if($(this).hasClass("bank-pay-btn")){
      getBIzzSn(that);
    }
  }
  //去付款
  function getBIzzSn(that) {
    var billId = $(that).data("bill");//当前账单数据
    var txt = "";//当前账单类型
    var typeTradeSn=0;
    $.each(traderType, function (k, v) {
      if (v == billId.tradeType) {
        txt = k;
      }
    });

    $.ajax(tokenAjax({
      type:"POST",
      url:QHConfig.url.accountBillId+billId.id,
      contentType: "application/json;charset=UTF-8",
      dataType:"json",
      success:function(res){
        var payUrl = "";
        var msg = res.data;
        if(res.status==400){
          layer.msg(res.message)
        }else{
          if(billId.tradeType == "充值"){
            payUrl = "tpl/project-recharge/project-recharge.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance+ "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&userCode=" + userCode;
          }else{
            payUrl = "tpl/buyer-pay/buyer-pay.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance
              + "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&accountName=" + billId.oppositeAccountUserCode + "&userCode=" + manageDetail.userCode + "&bizzSys=" + msg.bizzSys+"&tradeMemo="+billId.tradeMemo+"&formBill=true";
          }
          layerNew2(payUrl);
        }
      }
    }));
  }
  //跳转到支付页面
  function layerNew2(url) {
    parent.layer.open({
      title: false,
      shade: 0.8,
      move: false,
      closeBtn: 0,
      resize: false,
      scrollbar: false,
      type: 2,
      area: ['100%', '100%'],
      content: url,
      end:function() {
        window.location.reload();
      }
    })
  }
  //交易关闭
  function clickCloseFun(that) {
    var billId = $(that).data("bill");//当前账单数据
    layer.confirm("您确定要关闭交易吗？关闭后，不能恢复", {
      btn: ["确定关闭", "取消"],
      title: "温馨提示"
    }, function () {
      $.ajax(tokenAjax({
        type: "PUT",
        url: QHConfig.url.billClose + "?accountBillId=" + billId.id,
        contentType: "application/json;charset=UTF-8",
        success: function (res) {
          if (res.message == "success") {
            tableRefresh();
          } else {
            layer.msg(res.message);
          }
        },
        error: function () {
          layer.alert("网络错误");
        }
      }));
      layer.closeAll();
    });
  }
  function tableRefresh() {
    $("#id-trading-record").bootstrapTable("refresh");
  }
}
//交易类型模板
function tradeTypeFmt(val, row, index) {
  if(row.oppositeAccountRealName==null){
    row.oppositeAccountRealName="";
  }
  return `<span class="transaction-type">${row.tradeType}</span><div class="transaction-card">${row.oppositeAccountRealName}</div>`
}
//操作类型模板
function handleFmt(val, row, index) {
  if ((row.status == "等待付款"&&row.fundFlow=="资金流出")||(row.status == "等待付款"&&row.tradeType=="充值")) {
    return `<span class="close-trading"  data-bill='${JSON.stringify(row)}'>关闭交易</span><input class="bank-pay-btn" type="button"  data-bill='${JSON.stringify(row)}' value="付款"/>`
  } else {
    return ``
  }
}
